﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Crypto.SMCrypto;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.AppointAPI.Qingdao;
using AJWPFAdmin.Services.AppointAPI.Qingdao.Model;
using AJWPFAdmin.Services.EF;
using AJWPFAdmin.Services.EF.TableExts;
using Azure;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.Vml;
using FluentFTP;
using Masuit.Tools;
using Masuit.Tools.Net;
using Masuit.Tools.Reflection;
using MaterialDesignThemes.Wpf;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Ocsp;
using Prism.Ioc;
using System.Text;
using System.Web;

namespace AJWPFAdmin.Services.AppointAPI
{
    public class QingdaoAppointAPI : AppointAPIBase
    {
        private APIConfig _apiConfig;
        private IQingdaoApiImplement _qingdaoApiImplement;

        public QingdaoAppointAPI(ApplicationType appType,
            SystemConfigDictionary cfg,
            IContainerProvider svcProvider) : base(appType, cfg, svcProvider)
        {
            if (svcProvider.IsRegistered<IQingdaoApiImplement>())
            {
                _qingdaoApiImplement = svcProvider.Resolve<IQingdaoApiImplement>();
            }
        }

        private static readonly Dictionary<CarPlateColor, string> _customCarPlateColorMaps = new Dictionary<CarPlateColor, string>
        {
            {CarPlateColor.蓝牌, "0"},
            {CarPlateColor.黄牌, "1"},
            {CarPlateColor.白牌, "2"},
            {CarPlateColor.黑牌, "3"},
            {CarPlateColor.其他, "5"},
            {CarPlateColor.新能源绿牌, "6"},
            {CarPlateColor.新能源黄牌, "6"},
        };

        private static readonly List<string> _customCarTypes = new List<string>
        {
            "K", // 客车
            "H", // 货车
            "Q", // 牵引车
            "Z", // 专项作业车
            "D", // 电车
            "M", // 摩托车
            "N", // 三轮汽车
            "T", // 拖拉机
            "J", // 轮式机械
            "G", // 全挂车
            "B",// 半挂车
            "X", // 其他

        };


        protected override void OnAPILogsRaised(PassagewayDirection? direction,
            string logs)
        {
            base.OnAPILogsRaised(direction, logs);
        }

        public QingdaoBaseCommonReq WrapRequest(object req)
        {
            return new QingdaoBaseCommonReq { encryptData = SM2.EncryptToBase64(CommonUtil.AJSerializeObject(req), _apiConfig.publicKey), source = _apiConfig.clientId, version = _apiConfig.version };
        }

        /// <summary>
        /// 车辆信息-进出厂车
        /// </summary>
        /// <param name="params"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private async Task<ProcessResult> UploadvehicleInfoAsync(CarInfoParams @params, ProcessResult result)
        {
            try
            {
                var carNo = @params.CarInfo.CarNo;
                var attachFile = @params.CarInfo.GetFileOfPropertyName(nameof(Car.Attachments));
                var inventoryFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, attachFile));

                var noAttachments = string.IsNullOrEmpty(inventoryFile);

                var vehicleLicenseFile = @params.CarInfo.GetFileOfPropertyName(nameof(Car.VehicleLicense));
                var drivingLicenseFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, vehicleLicenseFile));

                var noLicense = string.IsNullOrEmpty(drivingLicenseFile);

                if (string.IsNullOrWhiteSpace(@params.CarInfo.VIN)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.UsageDescCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.EngineNo)
                    //|| string.IsNullOrWhiteSpace(@params.CarInfo.EngineModel)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.CarBrandModel)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.FuelTypeCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.TruckTypeCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.TeamName)
                    || (noAttachments || noLicense)
                    || @params.CarInfo.RegDate == null
                    )
                {
                    result.SetError("信息不齐");
                  _logger.Error($"QingdaoAppointAPI--UploadvehicleInfoAsync -青岛市-error:  @params信息不齐,请求信息{CommonUtil.AJSerializeObject(@params.CarInfo)}");
                    return result;
                }

                var inventoryFileNo = string.Empty;
                var inventoryFileReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = inventoryFile
                };
                //var inventoryFileReqWrapped = WrapRequest(inventoryFileReq);
                var inventoryFileResWrapped = await _qingdaoApiImplement.PostFileInfo(inventoryFileReq);
                if (inventoryFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadvehicleInfoAsync-PostFileInfo 上传车辆随车清单附件失败：解密状态码:{inventoryFileResWrapped.Code}，解析错误信息:{inventoryFileResWrapped.Msg}");
                    result.SetError("上传车辆随车清单附件失败");
                    return result;
                }
                inventoryFileNo = inventoryFileResWrapped.encryptData;


                var drivingLicenseFileNo = string.Empty;
                var drivingLicenseReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = drivingLicenseFile
                };

                //var drivingLicenseFileReqWrapped = WrapRequest(drivingLicenseReq);
                var drivingLicenseFileResWrapped = await _qingdaoApiImplement.PostFileInfo(drivingLicenseReq);
                if (drivingLicenseFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadvehicleInfoAsync-PostFileInfo 上传车辆行驶证附件失败：解密状态码:{drivingLicenseFileResWrapped.Code}，解析错误信息:{drivingLicenseFileResWrapped.Msg}");
                    result.SetError("上传行驶证附件失败");
                    return result;
                }

                drivingLicenseFileNo = drivingLicenseFileResWrapped.encryptData;


                var truckType = "x";
                if(!string.IsNullOrWhiteSpace(@params.CarInfo.TruckTypeCode))
                {
                    var firstCode = @params.CarInfo.TruckTypeCode.Substring(0,1);
                    if (_customCarTypes.Contains(firstCode))
                        truckType = firstCode;
                }
                  
                var req = new QingdaoUploadVehicleInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    carNo = @params.CarInfo.CarNo,
                    carColour = _customCarPlateColorMaps[@params.CarInfo.PlateColor],
                    vin = @params.CarInfo.VIN,
                    emissionStandard = @params.CarInfo.EmissionStandard.GetDescription(),
                    registerTime = @params.CarInfo.RegDate?.ToString("yyyy-MM-dd"),
                    carType = truckType,
                    fuelType = @params.CarInfo.FuelTypeCode,
                    useCharacter = @params.CarInfo.UsageDescCode,
                    engineNo = @params.CarInfo.EngineNo,
                    engineModel = @params.CarInfo.EngineNo,
                    carModel = @params.CarInfo.CarBrandModel,
                    fleetName = @params.CarInfo.TeamName,
                    inventory = inventoryFileNo,
                    drivingLicense = drivingLicenseFileNo
                };

                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostVehicleInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadvehicleInfoAsync-success-青岛市-上传场内车辆信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadvehicleInfoAsync -青岛市-error: {res.Msg}");
                }

               
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadvehicleInfoAsync 青岛市-error: {ex.Message}");
            }
            return result;

        }

        private async Task<ProcessResult> UploadvehicleSubmitAsync(CarInfoParams @params, ProcessResult result)
        {
            try
            {
                var carNo = @params.CarInfo.CarNo;
                var attachFile = @params.CarInfo.GetFileOfPropertyName(nameof(Car.Attachments));
                var inventoryFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, attachFile));

                var noAttachments = string.IsNullOrEmpty(inventoryFile);

                var vehicleLicenseFile = @params.CarInfo.GetFileOfPropertyName(nameof(Car.VehicleLicense));
                var drivingLicenseFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, vehicleLicenseFile));

                var noLicense = string.IsNullOrEmpty(drivingLicenseFile);

                if (string.IsNullOrWhiteSpace(@params.CarInfo.VIN)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.UsageDescCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.EngineNo)
                    //|| string.IsNullOrWhiteSpace(@params.CarInfo.EngineModel)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.CarBrandModel)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.FuelTypeCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.TruckTypeCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.TeamName)
                    || (noAttachments || noLicense)
                    || @params.CarInfo.RegDate == null
                    )
                {
                    result.SetError("信息不齐");
                    _logger.Error($"QingdaoAppointAPI--UploadvehicleSubmitAsync -青岛市-error:  @params信息不齐,请求信息{CommonUtil.AJSerializeObject(@params.CarInfo)}");
                    return result;
                }
                
                var inventoryFileNo = string.Empty;
                
                var inventoryFileReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = inventoryFile
                };
                //var inventoryFileReqWrapped = WrapRequest(inventoryFileReq);
                var inventoryFileResWrapped = await _qingdaoApiImplement.PostFileInfo(inventoryFileReq);
                if (inventoryFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadvehicleSubmitAsync-PostFileInfo 上传车辆随车清单附件失败：解密状态码:{inventoryFileResWrapped.Code}，解析错误信息:{inventoryFileResWrapped.Msg}");
                    result.SetError("上传车辆随车清单附件失败");
                    return result;
                }
                inventoryFileNo = inventoryFileResWrapped.encryptData;


                var drivingLicenseFileNo = string.Empty;
                
                var drivingLicenseReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = drivingLicenseFile
                };

                //var drivingLicenseFileReqWrapped = WrapRequest(drivingLicenseReq);
                var drivingLicenseFileResWrapped = await _qingdaoApiImplement.PostFileInfo(drivingLicenseReq);
                if (drivingLicenseFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadvehicleSubmitAsync-PostFileInfo 上传车辆行驶证附件失败：解密状态码:{drivingLicenseFileResWrapped.Code}，解析错误信息:{drivingLicenseFileResWrapped.Msg}");
                    result.SetError("上传行驶证附件失败");
                    return result;
                }

                drivingLicenseFileNo = drivingLicenseFileResWrapped.encryptData;


                var truckType = "x";
                if (!string.IsNullOrWhiteSpace(@params.CarInfo.TruckTypeCode))
                {
                    var firstCode = @params.CarInfo.TruckTypeCode.Substring(0, 1);
                    if (_customCarTypes.Contains(firstCode))
                        truckType = firstCode;
                }

                var req = new QingdaoUploadVehicleInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    carNo = @params.CarInfo.CarNo,
                    carColour = _customCarPlateColorMaps[@params.CarInfo.PlateColor],
                    vin = @params.CarInfo.VIN,
                    emissionStandard = @params.CarInfo.EmissionStandard.GetDescription(),
                    registerTime = @params.CarInfo.RegDate?.ToString("yyyy-MM-dd"),
                    carType = truckType,
                    fuelType = @params.CarInfo.FuelTypeCode,
                    useCharacter = @params.CarInfo.UsageDescCode,
                    engineNo = @params.CarInfo.EngineNo,
                    engineModel = @params.CarInfo.EngineNo,
                    carModel = @params.CarInfo.CarBrandModel,
                    fleetName = @params.CarInfo.TeamName,
                    inventory = inventoryFileNo,
                    drivingLicense = drivingLicenseFileNo
                };

                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostVehicleSubmit(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadvehicleSubmitAsync-success-青岛市-上传场内车辆信息审核成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadvehicleSubmitAsync -上传场内车辆信息审核error: {res.Msg}");
                }


            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadvehicleInfoAsync 青岛市-error: {ex.Message}");
            }
            return result;

        }

        /// <summary>
        /// 厂内运输车辆信息
        /// </summary>
        /// <param name="params"></param>
        /// <param name="result"></param>
        /// <returns></returns>

        private async Task<ProcessResult> UploadTruckInfoAsync(CarInfoParams @params, ProcessResult result)
        {
            try
            {
                
                if (string.IsNullOrWhiteSpace(@params.CarInfo.VIN)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.EngineNo)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.FuelTypeCode)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.CarBrandModel)
                    )
                {
                    result.SetError("信息不齐");
                    _logger.Error($"QingdaoAppointAPI--UploadTruckInfoAsync -青岛市-error:  @params信息不齐,请求信息{CommonUtil.AJSerializeObject(@params.CarInfo)}");
                    return result;
                }
                var carNo = @params.CarInfo.CarNo;
                var attachFile = @params.CarInfo.GetFileOfPropertyName(nameof(Car.Attachments));
                var inventoryFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, attachFile));
                var req = new QingdaoUploadTruckInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    entNo = _apiConfig.companycode,
                    vin = @params.CarInfo.VIN,
                    productionTime = @params.CarInfo.ProductionDate?.ToString("yyyy-MM-dd"),
                    engineNo = @params.CarInfo.EngineNo,
                    fuelType = @params.CarInfo.FuelTypeCode,
                    emissionStandard = @params.CarInfo.EmissionStandard.GetDescription(),
                    enteringTime = @params.CarInfo.CreateDate.ToString("yyyy-MM-dd"),
                    inventory = inventoryFile,
                    carModel = @params.CarInfo.CarBrandModel,
                    protectionNo = @params.CarInfo.EnvRegCode,
                    //carNo = @params.CarInfo.CarNo,
                    //registerTime = @params.CarInfo.RegDate?.ToString("yyyy-MM-dd"),
                    //drivingLicense = drivingLicenseFile,
                    //outTime = "出厂日期",
                    //useType = "车辆性质类型"
                };

                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostTruckInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadTruckInfoAsync-success-青岛市-上传场内运输车辆信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadTruckInfoAsync -青岛市-error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadTruckInfoAsync 青岛市-error: {ex.Message}");
            }
            return result;

        }

        /// <summary>
        /// 场内非道路移动机械信息
        /// </summary>
        /// <param name="params"></param>
        /// <param name="result"></param>
        /// <returns></returns>

        private async Task<ProcessResult> UploadNonRoadMechanicsInfoAsync(CarInfoParams @params, ProcessResult result)
        {
            try
            {
                var carNo = @params.CarInfo.CarNo;
                var nameplatePath = @params.CarInfo.GetFileOfPropertyName(nameof(Car.Nameplate));
                var engineNameplatePath = @params.CarInfo.GetFileOfPropertyName(nameof(Car.EngineNameplate));


                var nameplateFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, nameplatePath));
                var engineNameplateFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, engineNameplatePath));


                var noEngineNameplate = string.IsNullOrEmpty(engineNameplateFile);
                var noNameplate = string.IsNullOrEmpty(nameplateFile);
                if (
                      string.IsNullOrWhiteSpace(@params.CarInfo.EngineNo)
                    || string.IsNullOrWhiteSpace(@params.CarInfo.FuelTypeCode)
                    //|| string.IsNullOrWhiteSpace(@params.CarInfo.CarBrandModel)
                    /*string.IsNullOrWhiteSpace(@params.CarInfo.VIN)*/
                    || (noEngineNameplate || noNameplate))
                    
                {
                    result.SetError("信息不齐");
                    _logger.Error($"QingdaoAppointAPI--UploadNonRoadMechanicsInfoAsync -青岛市-error:  @params信息不齐,请求信息{CommonUtil.AJSerializeObject(@params.CarInfo)}");
                    return result;
                }
                

                var nameplateNameplateFileReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = nameplateFile
                };
                var nameplateNameplateFileResWrapped = await _qingdaoApiImplement.PostFileInfo(nameplateNameplateFileReq);
                if (nameplateNameplateFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadNonRoadMechanicsInfoAsync-PostFileInfo 场内非道路移动机械信息照片上传失败：状态码:{nameplateNameplateFileResWrapped.Code}，解析错误信息:{nameplateNameplateFileResWrapped.Msg}");
                    result.SetError("场内非道路移动机械信息-铭牌照片上传失败");
                    return result;
                }

                var engineNameplateNameplateFileReq = new QingdaoUploadFileInfoReq
                {
                    fileType = "1",
                    file = engineNameplateFile
                };
                var engineNameplateNameplateFileResWrapped = await _qingdaoApiImplement.PostFileInfo(engineNameplateNameplateFileReq);
                if (engineNameplateNameplateFileResWrapped.Code != 200)
                {
                    _logger.Error($"UploadNonRoadMechanicsInfoAsync-PostFileInfo 场内非道路移动机械信息照片上传失败：状态码:{engineNameplateNameplateFileResWrapped.Code}，解析错误信息:{engineNameplateNameplateFileResWrapped.Msg}");
                    result.SetError("场内非道路移动机械信息-发动机铭牌照片上传失败");
                    return result;
                }



                var req = new QingdaoUploadNonRoadMechanicsInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    entNo = _apiConfig.companycode,
                    productionTime = @params.CarInfo.ProductionDate?.ToString("yyyy-MM-dd"),
                    emissionStandard = @params.CarInfo.EmissionStandard.GetDescription(),
                    fuelType = @params.CarInfo.FuelTypeCode,
                    mechanicsType = ((int)@params.CarInfo.MachineType.GetValueOrDefault()).ToString(),
                    pin = @params.CarInfo.PIN,
                    machineModel = @params.CarInfo.MachineModel,
                    engineModel = @params.CarInfo.EngineModel,
                    engineManufacturer = @params.CarInfo.EngineManufacturer,
                    engineNumber = @params.CarInfo.EngineNo,
                    allNameplate = nameplateNameplateFileResWrapped.encryptData,
                    engineNameplate = engineNameplateNameplateFileResWrapped.encryptData,
                    enteringTime = @params.CarInfo.CreateDate.ToString("yyyy-MM-dd"),
                    protectionNo = @params.CarInfo.EnvRegCode,
                    //label = "机械环保信息标签",
                    //affiliationName = "所属人(单位)",
                    //outTime = "出厂日期",
                    //useType = "1",
                    //affiliationPhone = "所属人电话",
                    //locateDeviceNo = "定位设备编号"
                };
                _logger.Error($"QingdaoAppointAPI--UploadNonRoadMechanicsInfoAsync -青岛市-请求信息{CommonUtil.AJSerializeObject(req)}");
                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostNonRoadMechanicsInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadNonRoadMechanicsInfoAsync-success-青岛市-上传场内非道路移动机械信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadNonRoadMechanicsInfoAsync -青岛市-error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadNonRoadMechanicsInfoAsync 青岛市-error: {ex.Message}");
            }
            return result;

        }
        public override async Task<ProcessResult> UploadCarInfoAsync(CarInfoParams @params)
        {
            var result = new ProcessResult ();
            if (@params == default || @params?.CarInfo == null)
            {
                result.SetError("参数错误");
                _logger.Error($"QingdaoAppointAPI--UploadCarInfoAsync error: @params or @params?.CarInfo  is null");
            }

            switch (@params.CarInfo.TypeId)
            {
                case (long)CarTypeEnum.进出厂车:
                    result = await UploadvehicleInfoAsync(@params, result);
                    break;

                case (long)CarTypeEnum.厂内运输车:
                    result = await UploadTruckInfoAsync(@params, result);
                    break;

                case (long)CarTypeEnum.非道路移动机械:
                    result = await UploadNonRoadMechanicsInfoAsync(@params, result);
                    break;

                default:
                    result.SetSuccess();
                    break;
            }
            await UploadvehicleSubmitAsync(@params, result);
            return result;
        }

        public override Task<ProcessResult> UploadComanyInfoAsync(string @params)
        {
            return Task.FromResult(ProcessResult.DefaultSuccess);
        }

        /// <summary>
        /// 出入口信息(本地数据保存至数据库之后),上传到第三方接口
        /// </summary>
        /// <returns></returns>
        public override async Task<ProcessResult> UploadEntGateInfoAsync(WatchhouseInfoParams @params)
        {
            var result = new ProcessResult();
            try
            {
                if (@params == default)
                {
                    result.SetError("@params is null");
                    _logger.Error($"QingdaoAppointAPI--UploadEntGateInfoAsync error: req is null");
                }
                var req = new QingdaoUploadEntGateInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    entGate = _apiConfig.companycode,
                    gateName = @params.Watchhouse.Name,
                    gateNo = @params.Watchhouse.Code,
                    gateLon = @params.Watchhouse.Longitude.ToString(),
                    gateLat = @params.Watchhouse.Latitude.ToString(),
                    gateNum = @params.Watchhouse.PassagewaySum,
                };
                var reqWrapped = WrapRequest(req);
                _logger.Info($"QingdaoAppointAPI--UploadEntGateInfoAsync-请求加密信息-青岛市-出入口信息{CommonUtil.AJSerializeObject(reqWrapped)}!");
                var res = await _qingdaoApiImplement.PostEntGateInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadEntGateInfoAsync-success-青岛市-上传出入口信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadEntGateInfoAsync -青岛市-error: {res.Msg}   --res{CommonUtil.AJSerializeObject(req)} ---回执 {CommonUtil.AJSerializeObject(res)}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadEntGateInfoAsync 青岛市-error: {ex.Message}");
            }

            return result;
        }

        public override async Task<ProcessResult> UploadDeviceInfoAsync(DeviceInfoParams @params)
        {
            var result = new ProcessResult();
            try
            {
                if (@params.Device.Type >= DeviceType.高频读头)
                {
                    result.SetSuccess();
                    return result;
                }
                if (@params.Operation == DataOperationType.移除)
                {
                    result.SetSuccess();
                    return result;
                }

                if (@params == default)
                {
                    result.SetError("@params is null");
                    _logger.Error($"QingdaoAppointAPI--UploadDeviceInfoAsync error: req is null");
                }
                var req = new QingdaoUploadBindingInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    entNo = _apiConfig.companycode,
                    gatNo = @params.Watchhouse.Code,
                    bindingNo = @params.Device.Code,
                    bindingName = @params.Device.Name,
                    devBrand = @params.Device.Type.ToString(),
                    devNo = @params.Device.DevNo,
                };
                var reqWrapped = WrapRequest(req);
                _logger.Info($"QingdaoAppointAPI--UploadDeviceInfoAsync-请求加密信息-青岛市-企业门禁道闸信息{CommonUtil.AJSerializeObject(reqWrapped)}!");
                var res = await _qingdaoApiImplement.PostEntGateInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadDeviceInfoAsync-success-青岛市-上传企业门禁道闸信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadDeviceInfoAsync -青岛市-error: {res.Msg}");
                }


            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadDeviceInfoAsync error: {ex.Message}");
            }
            return result;
        }

        public override async Task<ProcessResult> UploadShippingRecordAsync(ShippingRecordParams @params)
        {
            var result = new ProcessResult();
            try
            {
                var carTailFileNo = string.Empty;
                var (carHead, _,_) = @params.Record.GetWatchPositionImageFile(@params.Record.Direction);
                _logger.Info($"UploadShippingRecordAsync-PostFileInfo-request{CommonUtil.AJSerializeObject(@params.Record)}");
                _logger.Info($"UploadShippingRecordAsync-PostFileInfo-carTail的值：{carHead}");
                await Task.Delay(3*1000);
                var carNo = @params.Record.CarNo;

                var carTailFile = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, carHead));

                if (!string.IsNullOrEmpty(carTailFile))
                {
                    
                    var carTailFileReq = new QingdaoUploadFileInfoReq
                    {
                        fileType = "2",
                        file = carTailFile
                    };
                    //var carTailFileReqWrapped = WrapRequest(carTailFileReq);
                    var carTailFileResWrapped = await _qingdaoApiImplement.PostFileInfo(carTailFileReq);
                    if(carTailFileResWrapped.Code!=200)
                    {
                        _logger.Error($"UploadShippingRecordAsync-PostFileInfo 车辆进出信息-通行照片上传失败：状态码:{carTailFileResWrapped.Code}，解析错误信息:{carTailFileResWrapped.Msg}");
                        result.SetError("车辆进出信息-通行照片上传失败");
                        return result;
                    }

                    carTailFileNo = carTailFileResWrapped.encryptData;
                    _logger.Info($"QingdaoAppointAPI--UploadShippingRecordAsync-carTail-success-青岛市-车辆进出信息-通行照片上传成功!");
                }
                else
                {
                    _logger.Error($"QingdaoAppointAPI--UploadShippingRecordAsync-carTail-fail-青岛市-车辆进出信息-通行照片上传失败，原因：本地车身图片路径{carHead}不存在!");
                     result.SetError($"车辆进出信息-通行照片-本地车身图片路径:{carHead}不存在");
                    return result;
                }
                var req = new QingdaoUploadShippingRecordInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    entNo = _apiConfig.companycode,
                    entranceId = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.WatchhouseCode : @params.Record.OutWatchhouseCode,
                    bindingNo = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.PassagewayCode : @params.Record.OutPassagewayCode,
                    type = @params.Record.Direction == PassagewayDirection.进 ? "1" : "2",
                    accessTime = @params.Record.Direction == PassagewayDirection.进
                                   ? @params.Record.ShipStartDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss")
                                   : @params.Record.ShipEndDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"),
                    carNo = @params.Record.CarNo,
                    carColour = _customCarPlateColorMaps[@params.Record.PlateColor],
                    carVin = @params.Record.VIN,
                    imgPath = carTailFileNo,
                    goodsName = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.InGoodsName : @params.Record.OutGoodsName,
                    weight = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.InGoodsVolume.ToDouble() : (double)@params.Record.OutGoodsVolume,
                };
                var reqs = new List<QingdaoUploadShippingRecordInfoReq> { req };

               
                var reqWrapped = WrapRequest(reqs);
                _logger.Info($"QingdaoAppointAPI--UploadShippingRecordAsync-请求加密信息-青岛市-门禁过车信息{CommonUtil.AJSerializeObject(reqWrapped)}!");
                var res = await _qingdaoApiImplement.PostShippingRecordInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadShippingRecordAsync-success-青岛市-门禁过车信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadShippingRecordAsync error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadShippingRecordAsync error: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 排放超标信息(本地数据保存至数据库之后),上传到第三方接口
        /// </summary>
        /// <returns></returns>
        public override async Task<ProcessResult> UploadEmiRiseRecordInfoAsync(EmiRiseRecordParams @params)
        {
            var result = new ProcessResult();
            try
            {
                if (@params == default)
                {
                    result.SetError("@params is null");
                    _logger.Error($"QingdaoAppointAPI--UploadEmiRiseRecordInfoAsync error: req is null");
                }
                if (@params.EmiRiseRecord.EndTime == default)
                    @params.EmiRiseRecord.EndTime = DateTime.Now;

                //var checkCarInfoReq = new QingdaoCheckCarInfoReq
                //{
                //    clientId = _apiConfig.clientId,
                //    clientSecret = _apiConfig.clientSecret,
                //    entNo = _apiConfig.companycode,
                //    carNo = @params.EmiRiseRecord.CarNo,
                //    carColour = _customCarPlateColorMaps[@params.CarInfo.PlateColor],

                //};
                //var checkCarInfoReqWrapped = WrapRequest(checkCarInfoReq);
                //var checkCarInfoRes = await _qingdaoApiImplement.CheckCarInfo(checkCarInfoReqWrapped);
                //if (checkCarInfoRes.Code == 200)
                //{
                //    result.SetSuccess();

                //}
                //else
                //{

                //}

                var req = new QingdaoEmissionExceedanceVerificationInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    carNo = @params.EmiRiseRecord.CarNo,
                    carColour = _customCarPlateColorMaps[@params.CarInfo.PlateColor],
                    vin = @params.CarInfo.VIN,
                    emissionStandard = @params.CarInfo.EmissionStandard.GetDescription(),
                   fuelType = @params.CarInfo.FuelTypeCode,
                   //overproofVerifyResult = @params.EmiRiseRecord.OverproofVerifyResult.ToString(),
                   overproofVerifyResult = "1",
                   verifyTime = @params.EmiRiseRecord.StartTime.ToString("yyyy-MM-dd"),
                   entNo = _apiConfig.companycode,
                    entName = _apiConfig.companyname,
                    exceedInfo = @params.EmiRiseRecord.ExceedInfo??"无",
                    exceedFlag = @params.EmiRiseRecord.ExceedFlag.ToString()??"2",
                   startTime = @params.EmiRiseRecord.StartTime.ToString("yyyy-MM-dd"),
                    endTime = @params.EmiRiseRecord.EndTime.Value.ToString("yyyy-MM-dd"),
                };
                _logger.Error($"QingdaoAppointAPI--UploadEmiRiseRecordInfoAsync -请求参数: {CommonUtil.AJSerializeObject(req)}");
                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostEmissionExceedanceVerificationInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadEmiRiseRecordInfoAsync-success-青岛市-上传排放超标信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadEmiRiseRecordInfoAsync -青岛市-error: {res.Msg}   --res{CommonUtil.AJSerializeObject(res)} ---回执 {CommonUtil.AJSerializeObject(res)}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadEmiRiseRecordInfoAsync 青岛市-error: {ex.Message}");
            }

            return result;
        }

        public override async Task<ProcessResult> QueryExcessiveEmissionsListAsync(QueryIllegalVehicleParams @params)
        {
            var result = new ProcessResult();

            result.SetSuccess(new AJTableFetchResult
            {
                Total = 0,
                HasNext = false,
            });
            return result;

            try
            {
                if (@params == default)
                {
                    result.SetError("@params is null");
                    _logger.Error($"QingdaoAppointAPI--QueryExcessiveEmissionsListAsync error: req is null");
                }
                var req = new QingdaoEmissionExceedanceVerificationInfoReq
                {
                    clientId = _apiConfig.clientId,
                    clientSecret = _apiConfig.clientSecret,
                    carNo = @params.CarNo,
                    carColour = _customCarPlateColorMaps[@params.Color??CarPlateColor.其他],
                    vin = "1HGCM82633A004352",
                    emissionStandard = "6", // 国六
                    fuelType = "B", // 柴油
                    overproofVerifyResult = "1", // 不超标
                    verifyTime = "2023-11-23",
                    entNo = _apiConfig.companycode,
                    entName = _apiConfig.companyname,
                    exceedInfo = "超标原因",
                    exceedFlag = "1", // 已解除
                    startTime = @params.StartDate == null ? string.Empty : @params.StartDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"),
                    endTime = @params.EndDate == null ? string.Empty : @params.EndDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"),
                    //remark = "备注信息",
                };
                var reqWrapped = WrapRequest(req);
                var res = await _qingdaoApiImplement.PostEntGateInfo(reqWrapped);
                if (res.Code == 200)
                {
                    result.SetSuccess();
                    _logger.Info($"QingdaoAppointAPI--UploadEntGateInfoAsync-success-青岛市-上传出入口信息成功!");
                }
                else
                {
                    result.SetError(res.Msg);
                    _logger.Error($"QingdaoAppointAPI--UploadEntGateInfoAsync -青岛市-error: {res.Msg}");
                }
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"QingdaoAppointAPI--UploadEntGateInfoAsync 青岛市-error: {ex.Message}");
            }

            return result;
        }
        public override Task ConvertToCustomConfig(bool isReal)
        {
            _apiConfig = CommonUtil.TryGetJSONObject<APIConfig>(Config.StringValue) ?? new APIConfig();
            _customAPIConfig = _apiConfig;
            AutoUploadDataVerification = _apiConfig.AutoUploadDataVerification;

            if (isReal)
            {

            }
            else
            {
                _ = GetSchemas();
            }

            return Task.CompletedTask;
        }

        public new void Dispose()
        {

        }

        public class APIConfig : APIConfigBase
        {
            [DynamicFormItemDefine("接口地址")]
            public string url { get; set; }

            [DynamicFormItemDefine("接口用户名")]
            public string clientId { get; set; }

            [DynamicFormItemDefine("接口密码")]
            public string clientSecret { get; set; }

            [DynamicFormItemDefine("公钥")]
            public string publicKey { get; set; }

            [DynamicFormItemDefine("私钥")]
            public string privateKey { get; set; }

            [DynamicFormItemDefine("版本号")]
            public string version { get; set; }

            [DynamicFormItemDefine("企业名称")]
            public string companyname { get; set; }

            [DynamicFormItemDefine("企业简称")]
            public string companyjc { get; set; }

            [DynamicFormItemDefine("企业编码")]
            public string companycode { get; set; }

            //[DynamicFormItemDefine("统一信用代码")]
            //public string unifiedcreditcode { get; set; }

            //[DynamicFormItemDefine("法人代表")]
            //public string corpname { get; set; }

            //[DynamicFormItemDefine("行业类型编码")]
            //public string industrytypecode { get; set; }

            //[DynamicFormItemDefine("行业类型名称")]
            //public string industrytypename { get; set; }
            //[DynamicFormItemDefine("企业地址")]
            //public string address { get; set; }
            //[DynamicFormItemDefine("区县编码")]
            //public string countycode { get; set; }
            //[DynamicFormItemDefine("区县名称")]
            //public string countyname { get; set; }
            //[DynamicFormItemDefine("产能")]
            //public string cn { get; set; }
            //[DynamicFormItemDefine("监控设备数量")]
            //public string jksbsl { get; set; }
            //[DynamicFormItemDefine("企业评级")]
            //public string industry_type { get; set; }
            //[DynamicFormItemDefine("经度")]
            //public string lng { get; set; }
            //[DynamicFormItemDefine("纬度")]
            //public string lat { get; set; }
        }
    }
}
